package com.video.util;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;

/**
 * @author maomao
 */
@Data
@Slf4j
public class FetchVideoCover {

    private String ffmpegPath;

    public FetchVideoCover(String ffmpegPath) {
        this.ffmpegPath = ffmpegPath;
    }

    public void getCover(String videoInputPath, String coverOutputPath) throws IOException {
        List<String> command = new LinkedList<>();

        command.add(ffmpegPath);

        // 指定截取第1秒
        command.add("-ss");
        command.add("00:00:01");

        command.add("-y");
        command.add("-i");
        command.add(videoInputPath);

        command.add("-vframes");
        command.add("1");

        command.add(coverOutputPath);

        ProcessBuilder builder = new ProcessBuilder(command);
        Process process = builder.start();

        InputStream errorStream = process.getErrorStream();
        InputStreamReader inputStreamReader = new InputStreamReader(errorStream);
        BufferedReader br = new BufferedReader(inputStreamReader);

        String line = "";

        while ((line = br.readLine()) != null){}

        if (br != null) br.close();

        if (inputStreamReader != null) inputStreamReader.close();

        if (errorStream != null) errorStream.close();

        log.info("get cover page from video: {}", videoInputPath);
    }
}
